<?php
/**
 * Controller helper for checking form validation and setting form error
 * messages. Uses FlashMessenger helper.
 * 
 * @package disputeo
 * @version 1.0
 * @author jimmy.dixon
 */

class Disputeo_Controller_Helper_FormCheck extends Zend_Controller_Action_Helper_Abstract
{
    /**
     * @var Zend_Controller_Request_Abstract
     */
    protected $_request = null;
    
    /**
     * @var Zend_Controller_Action_Helper_Abstract
     */
    protected $_messenger = null;
    
    /**
     * @var Zend_Controller_Action
     */
    protected $_controller = null;

    /**
     * Initialise application resources
     */
    public function init()
    {
        $this->_request = Zend_Controller_Front::getInstance()->getRequest();
        $this->_messenger = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
        $this->_controller = $this->getActionController();
        $this->_controller->forms = array();
    }

    /**
     * Initialise application resources
     * @return boolean
     */
    public function direct($formName = null)
    {
        if (empty($this->_controller->forms[$formName])) {
            return false;
        }
        
        $form = $this->_controller->forms[$formName];
        if ($this->_request->isPost()) {
            if ($form->isValid($this->_request->getPost())) {
                $this->_setFormMessages($form);
                return true;
            }
        }
        $this->_setFormMessages($form);
        return false;
    }

    /**
     * Initialise application resources
     */
    public function register(Zend_Form $form)
    {
        $this->_controller->forms[$form->getName()] = $form;
        return $this;
    }
    
    /**
     * Initialise application resources
     */
    public function errorMessages()
    {
        $messages = current($this->_messenger->getMessages());
        if (is_array($messages)) {
            foreach ($messages as $form => $data) {
                if (strpos($form, 'Errors') === false) {
                    $errors = $messages[$form . 'Errors'];
                    if (isset($this->_controller->forms[$form])) {
                        $this->_controller->forms[$form]->setElementErrors($errors);
                        $this->_controller->forms[$form]->populate($data);
                    }
                }
            }
        }
    }

    /**
     * Initialise application resources
     */
    protected function _setFormMessages(Zend_Form $form)
    {
        $this->_messenger->addMessage(array(
            $form->getName() => $this->_request->getPost(),
            $form->getName() . 'Errors' => $form->getMessages()
        ));
    }
}
